package com.supor.aiot.home.ui.device;

import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.view.View;

import com.alibaba.android.arouter.facade.annotation.Route;
import com.android.baseconfig.common.utils.GsonUtil;
import com.android.baseconfig.common.utils.ToastUtils;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.supor.aiot.common.app.AppAgent;
import com.supor.aiot.common.app.Constants;
import com.supor.aiot.common.app.SuporPresenter;
import com.supor.aiot.common.arouter.PathUrl;
import com.supor.aiot.common.base.BaseMVVMActivity;
import com.supor.aiot.common.entity.DeviceInfo;
import com.supor.aiot.common.entity.ProductType;
import com.supor.aiot.common.entity.Result;
import com.supor.aiot.common.helper.ConfigActivityManager;
import com.supor.aiot.common.helper.GlobalDataCache;
import com.supor.aiot.common.interfaces.OnByItemFilterClickListener;
import com.supor.aiot.common.utils.NFCCheckUtils;
import com.supor.aiot.home.R;
import com.supor.aiot.home.apdater.NavigationAdapter;
import com.supor.aiot.home.apdater.NavigationContentAdapter;
import com.supor.aiot.home.databinding.ActivityAddDeviceBinding;
import com.supor.aiot.home.ui.device.config.InputWiFiActivity;
import com.supor.aiot.home.ui.device.config.NFCDeviceGuideActivity;
import com.supor.aiot.home.ui.device.config.NFCIntroduceActivity;
import com.supor.nfc.lib.utils.NfcUtils;

import java.util.ArrayList;

import androidx.annotation.NonNull;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

@Route(path = PathUrl.PATH_ADD_DEVICE)
public class AddDeviceActivity extends BaseMVVMActivity<AddDeviceViewModel, ActivityAddDeviceBinding> {

    private NavigationAdapter mNaviAdapter;
    private NavigationContentAdapter mContentAdapter;
    private int currentPosition = 0;
    private LinearLayoutManager layoutManager;
    private DeviceInfo device;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        ConfigActivityManager.addActivity(this);
    }

    @Override
    protected int resourceId() {
        return R.layout.activity_add_device;
    }

    @Override
    protected void initView() {
        super.initView();
        bindingView.toolbar.setIvLeftOnClickListener(v -> finish());
        bindingView.toolbar.setTvLeftOnClickListener(v -> finish());
        initRefreshView();
    }

    @Override
    protected void initData() {
        super.initData();
        viewModel.getAllProduct();

        viewModel.getBindResult().observe(this, result -> {
            if (result instanceof Result.Success) {
                GlobalDataCache.getBindDevice();
                // 跳转小程序
                if (Constants.Type.TYPE_VOLTAGE_POT.equalsIgnoreCase(device.model)) {
                    if (AppAgent.h5Debug) {
                        AppAgent.startDebugTiny(this, Constants.App.PAGE_DEVICE, GsonUtil.getInstance().toJson(device), "");
                    } else {
                        AppAgent.startDevicePage(Constants.App.TINY_DEVICE_VOLTAGE_POT, GsonUtil.getInstance().toJson(device));
                    }
                } else if (Constants.Type.TYPE_VOLTAGE_POT_C100.equalsIgnoreCase(device.model)) {
                    if (AppAgent.h5Debug) {
                        AppAgent.startDebugTiny(this, Constants.App.PAGE_DEVICE, GsonUtil.getInstance().toJson(device), "");
                    } else {
                        AppAgent.startDevicePage(Constants.App.TINY_DEVICE_VOLTAGE_POT_3L, GsonUtil.getInstance().toJson(device));
                    }
                } else if (Constants.Type.TYPE_ELECTRIC_SAUCEPAN.equalsIgnoreCase(device.model)) {
                    if (AppAgent.h5Debug) {
                        AppAgent.startDebugTiny(this, Constants.App.PAGE_DEVICE, GsonUtil.getInstance().toJson(device), "");
                    } else {
                        AppAgent.startDevicePage(Constants.App.TINY_ELECTRIC_SAUCEPAN, GsonUtil.getInstance().toJson(device));
                    }
                } else if (Constants.Type.TYPE_BLENDER_66R.equalsIgnoreCase(device.model)) {
                    if (AppAgent.h5Debug) {
                        AppAgent.startDebugTiny(this, Constants.App.PAGE_DEVICE, GsonUtil.getInstance().toJson(device), "");
                    } else {
                        AppAgent.startDevicePage(Constants.App.TINY_DEVICE_BLENDER_66R, GsonUtil.getInstance().toJson(device));
                    }
                } else if (Constants.Type.TYPE_BLENDER_65S.equalsIgnoreCase(device.model)) {
                    if (AppAgent.h5Debug) {
                        AppAgent.startDebugTiny(this, Constants.App.PAGE_DEVICE, GsonUtil.getInstance().toJson(device), "");
                    } else {
                        AppAgent.startDevicePage(Constants.App.TINY_DEVICE_BLENDER_65S, GsonUtil.getInstance().toJson(device));
                    }
                } else if (Constants.Type.TYPE_BLENDER_905S.equalsIgnoreCase(device.model)) {
                    if (AppAgent.h5Debug) {
                        AppAgent.startDebugTiny(this, Constants.App.PAGE_DEVICE, GsonUtil.getInstance().toJson(device), "");
                    } else {
                        AppAgent.startDevicePage(Constants.App.TINY_DEVICE_BLENDER_905S, GsonUtil.getInstance().toJson(device));
                    }
                } else if (Constants.Type.TYPE_BLENDER_906R.equalsIgnoreCase(device.model)) {
                    if (AppAgent.h5Debug) {
                        AppAgent.startDebugTiny(this, Constants.App.PAGE_DEVICE, GsonUtil.getInstance().toJson(device), "");
                    } else {
                        AppAgent.startDevicePage(Constants.App.TINY_DEVICE_BLENDER_906R, GsonUtil.getInstance().toJson(device));
                    }
                }

                // 销毁当前页面
                new Handler().postDelayed(() -> {
                    setResult(1);
                    finish();
                }, 1000);
            } else if (result instanceof Result.Error) {
                ToastUtils.getInstance().showCustomToast("绑定设备失败");
            }
        });
    }

    private void initRefreshView() {
        mNaviAdapter = new NavigationAdapter();
        layoutManager = new LinearLayoutManager(AppAgent.getApp());
        bindingView.xrvNavi.setLayoutManager(layoutManager);
        bindingView.xrvNavi.setOverScrollMode(View.OVER_SCROLL_NEVER);
        bindingView.xrvNavi.setAdapter(mNaviAdapter);

        mContentAdapter = new NavigationContentAdapter();
        LinearLayoutManager linearLayoutManager = new LinearLayoutManager(AppAgent.getApp());
        bindingView.xrvNaviDetail.setOverScrollMode(View.OVER_SCROLL_NEVER);
        bindingView.xrvNaviDetail.setLayoutManager(linearLayoutManager);
        bindingView.xrvNaviDetail.setAdapter(mContentAdapter);

        mNaviAdapter.setOnSelectListener(position -> {
            mContentAdapter.setBlankViewVisible(true);
            selectItem(position);
            moveToCenter(position);
            Integer titlePosition = viewModel.getTitlePositions().getValue().get(position);
            linearLayoutManager.scrollToPositionWithOffset(titlePosition, 0);
        });
        bindingView.xrvNaviDetail.addOnScrollListener(new RecyclerView.OnScrollListener() {
            @Override
            public void onScrolled(@NonNull RecyclerView recyclerView, int dx, int dy) {
                super.onScrolled(recyclerView, dx, dy);
                if (dx != 0 || dy != 0) {
                    mContentAdapter.setBlankViewVisible(false);
                }
                int itemPosition = linearLayoutManager.findFirstVisibleItemPosition();
                Integer integer = viewModel.getHashMap().get(itemPosition);
                if (integer != null && currentPosition != integer) {
                    selectItem(integer);
                    moveToCenter(integer);
                }
            }
        });
        bindingView.xrvNaviDetail.setOnItemClickListener(new OnByItemFilterClickListener() {
            @Override
            protected void onSingleClick(@NonNull BaseQuickAdapter<?, ?> adapter, View v,
                                         int position) {
                ProductType.ProductModel model = mContentAdapter.getItemData(position);
                Intent intent = new Intent(AddDeviceActivity.this, InputWiFiActivity.class);
                // 判断是否为NFC标签
                if (Constants.Type.TYPE_VOLTAGE_POT.equalsIgnoreCase(model.modelId)
                        || Constants.Type.TYPE_VOLTAGE_POT_C100.equalsIgnoreCase(model.modelId)
                        || Constants.Type.TYPE_ELECTRIC_SAUCEPAN.equalsIgnoreCase(model.modelId)
                        || Constants.Type.TYPE_BLENDER_66R.equalsIgnoreCase(model.modelId)
                        || Constants.Type.TYPE_BLENDER_65S.equalsIgnoreCase(model.modelId)
                        || Constants.Type.TYPE_BLENDER_905S.equalsIgnoreCase(model.modelId)
                        || Constants.Type.TYPE_BLENDER_906R.equalsIgnoreCase(model.modelId)) {
                    // 判断pid是否已经绑定
                    DeviceInfo deviceInfo = NFCCheckUtils.getDeviceInfoByPid(model.productId);
                    if (deviceInfo != null) {
                        // 如果绑定直接跳转
                        if (Constants.Type.TYPE_VOLTAGE_POT.equalsIgnoreCase(model.modelId)) {
                            AppAgent.startDevicePage(Constants.App.TINY_DEVICE_VOLTAGE_POT, GsonUtil.getInstance().toJson(deviceInfo));
                        } else if (Constants.Type.TYPE_VOLTAGE_POT_C100.equalsIgnoreCase(model.modelId)) {
                            AppAgent.startDevicePage(Constants.App.TINY_DEVICE_VOLTAGE_POT_3L, GsonUtil.getInstance().toJson(deviceInfo));
                        } else if (Constants.Type.TYPE_ELECTRIC_SAUCEPAN.equalsIgnoreCase(model.modelId)) {
                            AppAgent.startDevicePage(Constants.App.TINY_ELECTRIC_SAUCEPAN, GsonUtil.getInstance().toJson(deviceInfo));
                        } else if (Constants.Type.TYPE_BLENDER_66R.equalsIgnoreCase(model.modelId)) {
                            AppAgent.startDevicePage(Constants.App.TINY_DEVICE_BLENDER_66R, GsonUtil.getInstance().toJson(deviceInfo));
                        } else if (Constants.Type.TYPE_BLENDER_65S.equalsIgnoreCase(model.modelId)) {
                            AppAgent.startDevicePage(Constants.App.TINY_DEVICE_BLENDER_65S, GsonUtil.getInstance().toJson(deviceInfo));
                        } else if (Constants.Type.TYPE_BLENDER_905S.equalsIgnoreCase(model.modelId)) {
                            AppAgent.startDevicePage(Constants.App.TINY_DEVICE_BLENDER_905S, GsonUtil.getInstance().toJson(deviceInfo));
                        } else if (Constants.Type.TYPE_BLENDER_906R.equalsIgnoreCase(model.modelId)) {
                            AppAgent.startDevicePage(Constants.App.TINY_DEVICE_BLENDER_906R, GsonUtil.getInstance().toJson(deviceInfo));
                        }
                        return;
                    } else {
                        // 判断手机是否支持NFC
                        if (NfcUtils.NFC_STATE == 1) {
                            // NFC标签需登录
                            if (!AppAgent.isLogin()) {
                                SuporPresenter.getInstance().getCmccHelper().displayLogin(false);
                                return;
                            }
                            // 不支持，直接绑定,然后跳转详情页
                            device = new DeviceInfo();
                            device.mac = NFCCheckUtils.generateUid(model.productId, false);
                            device.pid = model.productId;

                            for (ProductType productType : GlobalDataCache.productTypeList) {
                                if (productType.Children == null) {
                                    continue;
                                }
                                for (ProductType.ProductModel child : productType.Children) {
                                    if (model.productId.equalsIgnoreCase(child.productId)) {
                                        device.crmModelName = child.crmModelName;
                                        device.type = child.modelTypeId;
                                        device.model = child.modelId;
                                        device.productUrl = child.modelPicture;
                                        device.productName = child.modelTypeName;
                                        device.offStatusText = child.remark;
                                        break;
                                    }
                                }
                            }

                            viewModel.bindNFCDevice(device.mac, device.model);
                            return;
                        }
                    }
                }
                // 判断是否为NFC模块
                if (Constants.Type.BLENDER_Q8.equalsIgnoreCase(model.modelId)
                        || Constants.Type.TYPE_ELECTRIC_SAUCEPAN_C18.equalsIgnoreCase(model.modelId)) {
                    // 手机不支持NFC，判断pid是否存在，存在直接跳小程序，不存在就跳转NFC智能使用说明页面
                    if (NfcUtils.NFC_STATE == 1) {
                        if (!AppAgent.isLogin()) {
                            SuporPresenter.getInstance().getCmccHelper().displayLogin(false);
                            return;
                        }
                        DeviceInfo deviceInfo = NFCCheckUtils.getDeviceInfoByPid(model.productId);
                        if (deviceInfo != null) {
                            // 如果绑定直接跳转
                            if (Constants.Type.BLENDER_Q8.equalsIgnoreCase(model.modelId)) {
                                AppAgent.startDevicePage(Constants.App.TINY_DEVICE_BLENDER, GsonUtil.getInstance().toJson(deviceInfo));
                            } else if (Constants.Type.TYPE_ELECTRIC_SAUCEPAN_C18.equalsIgnoreCase(model.modelId)) {
                                AppAgent.startDevicePage(Constants.App.TINY_DEVICE_ELECTRIC_SAUCEPAN_C18, GsonUtil.getInstance().toJson(deviceInfo));
                            }
                        } else {
                            // 不存在就跳转NFC智能使用说明页面
                            intent = new Intent(AddDeviceActivity.this, NFCIntroduceActivity.class);
                            Bundle bundle = new Bundle();
                            bundle.putString("productId", model.productId);
                            intent.putExtras(bundle);
                            startActivityForResult(intent, Constants.REQUEST_CODE);
                        }
                        return;
                    }
                }
                if (Constants.Type.BLENDER_Q8.equalsIgnoreCase(model.modelId)
                        || Constants.Type.TYPE_ELECTRIC_SAUCEPAN_C18.equalsIgnoreCase(model.modelId)
                        || Constants.Type.TYPE_VOLTAGE_POT.equalsIgnoreCase(model.modelId)
                        || Constants.Type.TYPE_VOLTAGE_POT_C100.equalsIgnoreCase(model.modelId)
                        || Constants.Type.TYPE_ELECTRIC_SAUCEPAN.equalsIgnoreCase(model.modelId)
                        || Constants.Type.TYPE_BLENDER_66R.equalsIgnoreCase(model.modelId)
                        || Constants.Type.TYPE_BLENDER_65S.equalsIgnoreCase(model.modelId)
                        || Constants.Type.TYPE_BLENDER_905S.equalsIgnoreCase(model.modelId)
                        || Constants.Type.TYPE_BLENDER_906R.equalsIgnoreCase(model.modelId)) {
                    intent = new Intent(AddDeviceActivity.this, NFCDeviceGuideActivity.class);
                    Bundle bundle = new Bundle();
                    bundle.putString("productId", model.productId);
                    intent.putExtras(bundle);
                }
                intent.putExtra(Constants.Key.PRODUCT_MODEL, model);
                startActivityForResult(intent, Constants.REQUEST_CODE);
                // activity.finish();
        }

        });
        onObserveViewModel();
    }

    private void onObserveViewModel() {
        // 左侧标题
        viewModel.getDataTitle().observe(this, dataBeans -> {
            mNaviAdapter.setNewData(dataBeans);
            selectItem(0);
        });
        // 右侧内容
        viewModel.getData().observe(this, list -> {
            if (list != null && list.size() > 0) {
                showContentView();
                mContentAdapter.setPositions((ArrayList<Integer>) viewModel.getTitlePositions().getValue());
                mContentAdapter.setNewData(list);
                mContentAdapter.notifyTitle(0);
            } else {
                showError();
            }
        });
    }

    private void selectItem(int position) {
        if (position < 0 || mNaviAdapter.getData().size() <= position) {
            return;
        }
        // Logc.e("selectItem: " + position);
        mNaviAdapter.getData().get(currentPosition).selected = false;
        mNaviAdapter.notifyItemChanged(currentPosition);
        currentPosition = position;
        mNaviAdapter.getData().get(position).selected = true;
        mNaviAdapter.notifyItemChanged(position);
        mContentAdapter.notifyTitle(viewModel.getPositionTitleMap().get(position));
    }

    /**
     * 将当前选中的item居中
     */
    private void moveToCenter(int position) {
        //将点击的position转换为当前屏幕上可见的item的位置以便于计算距离顶部的高度，从而进行移动居中
        View childAt = bindingView.xrvNavi.getChildAt(position - layoutManager.findFirstVisibleItemPosition());
        if (childAt != null) {
            int y = (childAt.getTop() - bindingView.xrvNavi.getHeight() / 2);
            bindingView.xrvNavi.smoothScrollBy(0, y);
        }
    }

    @Override
    protected void onRefresh() {
        viewModel.getAllProduct();
    }

    @Override
    public void updateNetStatus(int type) {

    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (Constants.REQUEST_CODE == requestCode) {
            if (resultCode == 1) {
                setResult(1);
                finish();
            }
        }
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        ConfigActivityManager.removeActivity(this);
    }
}
